import React from 'react';
import menuRoute from 'routes/menuRoute'
import FileSaver from 'file-saver'
import {Form, Button, Row, Col, Switch, Icon, Menu, Modal, message, Spin, Radio, Dropdown} from 'antd'
const RadioGroup = Radio.Group;
import HelpDocumentMenu from 'containers/setting/help-document-management/help-document-menu'
import documentService from 'containers/setting/help-document-management/help-document.service'
import 'styles/setting/help-document-management/help-document.scss'
import { connect } from 'react-redux'
import {messages} from "share/common";
import SSService from "../security-setting/security-setting.service";
import BaseService from "share/base.service";
import moment from "moment";
import 'styles/setting/help-document-management/help-document-content.scss'

class HelpDocument extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      releaseLoading: false,
      menuIsSorting: false,
      info: {},
      downloadLanguageVisible: false,
      downloadDoc: '',
      downloadLanguage: props.language.code,
      language: props.language.code,
    };
    this.languagesObj = {
      zh_cn: messages('basic-11.key140')/*简体中文*/,
      zh_tw: messages('basic-11.key141')/*繁体中文*/,
      en: messages('basic-11.key142')/*英文*/,
      ja: messages('basic-11.key143')/*日语*/,
      it_IT: messages('basic-11.key144')/*意大利语*/
    };
  }

  editCompanySecuritySetting = (params) => {
    this.setState({
      loading: true
    });
    SSService.updateCompanySecuritySetting(params)
      .then((response) => {
        message.success(messages('common.operate.success')/*操作成功*/);
        //重置redux
        BaseService.getCompany();
        this.setState({
          loading: false
        })
      }).catch(err => {
      this.setState({
        loading: false
      })
    })
  };

  //选择文档下载的语言
  selectDownloadLanguage = () => {
    this.setState({
      downloadLanguageVisible: true,
      downloadLanguage: 'zh_cn'
    })
  };

  //文档下载
  handleDownload = () => {
    const { downloadLanguage } = this.state;
    let languages = {
      zh_cn: messages('basic-11.key140')/*简体中文*/,
      en: messages('basic-11.key142')/*英文*/,
      ja: messages('basic-11.key143')/*日语*/
    };
    let params = {
      language: downloadLanguage
    };
    this.setState({ loading: true, downloadLanguageVisible: false });
    documentService.exportDocument(params).then(res => {
      let b = new Blob([res.data]);
      let name = `${languages[downloadLanguage]}${messages('basic-11.key149')/*文档*/}`;
      FileSaver.saveAs(b, `${name}.zip`);
      this.setState({ loading: false })
    }).catch(() => {
      this.setState({ loading: false })
    })
  };

  //发布到正式环境
  handleToProd = () => {
    Modal.confirm({
      title: messages('basic-11.key150')/*确定要更新吗？*/,
      content: messages('basic-11.key151')/*更新后，帮助文档所做的修改会更新到操作手册。*/,
      onOk: () => this.handleRelease()
    })
  };

  //发布
  handleRelease = () => {
    this.setState({ releaseLoading : true });
    documentService.handleRelease().then(() => {
      message.success(messages('basic-11.key152')/*更新成功*/);
      this.setState({ releaseLoading: false, });
    }).catch(() => {
      this.setState({ releaseLoading: false, });
    })
  };

  //选择目录
  handleMenuSelect = (info) => {
    let language = this.props.language.code;
    this.setState({ info, language});
  };

  onStatusChange = (status) => {
    const {company} = this.props;
    let title = status ? messages('basic-11.key153')/*启用后，将使用下方自定义的操作手册。*/ : messages('basic-11.key154')/*禁用后，将使用汇联易统一的操作手册。*/;
    Modal.confirm({
      title,
      onOk: () => {
        company.helpDocumentStatus = status;
        this.editCompanySecuritySetting(company)
      }
    });
  };


  //获取文档标题或内容
  getDocTitleOrContent = (list = [], language) => {
    let value = '';
    list.forEach(item => {
      if (item.language.toLowerCase() === language.toLowerCase())
        value = item.value
    });
    return value
  };

  //修改语言
  handleLanguageChange = (key) => {
    this.setState({
      language: key,
    })
  };

  handleEdit = () => {
    const {info} = this.state;
    this.context.router.push(menuRoute.getPageUrlByKey('help-document-edit').replace(':id', info.id))
  };

  handleHistory = () => {
    const {info} = this.state;
    this.context.router.push(menuRoute.getPageUrlByKey('help-document-history').replace(':id', info.id))
  };


  transformChar = (code) => {
    return code ? code.replace(/﹤/g, "<").replace(/﹥/g, ">") : "";
  };

  renderDropDown = () => {
    const {language, info} = this.state;
    let arr = [];
    if(info.i18n && info.i18n.docTitle){
      arr = info.i18n.docTitle.map(item => item.language.toLowerCase())
    }
    if(info.i18n && info.i18n.docContent){
      info.i18n.docContent.forEach(item => {
        let lan = item.language.toLowerCase();
        if(arr.indexOf(lan) === -1){
          arr.push(lan)
        }
      })
    }
    const languageMenu = (
      <Menu onClick={e => this.handleLanguageChange(e.key)}>
        {
          arr.map(item => {
            return <Menu.Item key={item}>{this.languagesObj[item]}</Menu.Item>
          })
        }
      </Menu>
    );
    return(
      <Dropdown overlay={languageMenu}>
        <a className="language">{this.languagesObj[language]}<Icon type="down" />
        </a>
      </Dropdown>
    )
  };
  render() {
    const { loading, menuIsSorting, info, releaseLoading, downloadLanguageVisible, downloadLanguage,
      language} = this.state;
    let {company, authPolicyAll} = this.props;
    return (
      <div className="help-document">
        <Spin spinning={loading}>
          <div className={`help-document-cover ${menuIsSorting ? 'show' : ''}`}
               onClick={() => this.setState({ menuIsSorting: false })} />
          <div className="header-container">
            <Button type="primary" loading={releaseLoading} onClick={this.handleToProd} disabled={!authPolicyAll}>
              {messages('basic-11.key155')/*内容更新到操作手册*/}
            </Button>
            <Button onClick={this.selectDownloadLanguage} style={{margin: "0 20px"}}>{messages('basic-11.key156')/*文档下载*/}</Button>
            <span>{messages('common.column.status')/*状态*/}：
              <Switch checked={company.helpDocumentStatus} onChange={this.onStatusChange} disabled={!authPolicyAll}/>
            </span>
          </div>
          <Row>
            <Col span={5} className="menu-container">
              <HelpDocumentMenu
                isSorting={menuIsSorting}
                selectedId={this.props.params.id}
                onSort={flag => this.setState({menuIsSorting: flag})}
                onMenuSelect={this.handleMenuSelect}
              />
            </Col>
              <Col span={19}>
                <div className="help-document-content">
                  <div className="content-header">
                    <Button type="primary" onClick={this.handleEdit} disabled={!authPolicyAll}>{messages('common.edit')/*编辑*/}</Button>
                    <Button className="history-button" onClick={this.handleHistory}>{messages('basic-11.key157')/*历史版本*/}</Button>
                  </div>
                  <div className="content-document">
                    <div className="document-header">
                      <span className="title">{info && info.i18n ? this.getDocTitleOrContent(info.i18n.docTitle, language) : ""}</span>
                      {this.renderDropDown()}
                    </div>
                    <div className="document-info">
                      <span className="update-time">{messages('basic-11.key107')/*更新时间*/}：{info.userName} {moment(info.lastUpdatedDate).format('YYYY-MM-DD HH:mm')}</span>
                    </div>
                    <div className="document-content"
                         dangerouslySetInnerHTML={{__html:
                             info && info.i18n ? this.transformChar(this.getDocTitleOrContent(info.i18n.docContent, language)) : ""}}/>
                  </div>
                </div>
              </Col>
          </Row>
        </Spin>

        <Modal visible={downloadLanguageVisible}
               title={messages('basic-11.key158')/*请选择文档下载语言*/}
               onOk={this.handleDownload}
               onCancel={() => this.setState({downloadLanguageVisible: false})}>
          <RadioGroup value={downloadLanguage}
                      onChange={e => this.setState({downloadLanguage: e.target.value})}>
            <Radio value="zh_cn">{messages('basic-11.key140')/*简体中文*/}</Radio>
            <Radio value="en">{messages('basic-11.key142')/*英文*/}</Radio>
            <Radio value="ja">{messages('basic-11.key143')/*日语*/}</Radio>
          </RadioGroup>
        </Modal>
      </div>
    )
  }
}

HelpDocument.contextTypes = {
  router: React.PropTypes.object
};

HelpDocument.propTypes = {};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    authPolicyAll: state.main.authPolicyAll,
    language: state.main.language,
  }
}

const WrappedHelpDocument = Form.create()(HelpDocument);
export default connect(mapStateToProps)(WrappedHelpDocument);
